﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace _51_AOP.Utility.Filter
{
    public class CustomExceptionFilterAttribute : Attribute, IExceptionFilter//, IAsyncExceptionFilter
    {
        private readonly IModelMetadataProvider _modelMetadataProvider;
        public CustomExceptionFilterAttribute(IModelMetadataProvider modelMetadataProvider) {
            this._modelMetadataProvider= modelMetadataProvider;
        }
        /// <summary>
        /// 当异常发生的时候，就会触发这里
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnException(ExceptionContext context)
        {
            Console.WriteLine("异常发生同步方法");
            if (context.ExceptionHandled == false)
            {
                if (isAjaxRequest(context.HttpContext.Request)) // 判断时候是Ajax请求
                {
                    // json返回
                    context.Result = new JsonResult(new Models.AjaxResult
                    {
                        Success = false,
                        Message = context.Exception.Message
                    });
                }
                else { 
                    // 页面请求
                    ViewResult result = new ViewResult { ViewName = "~/Views/Home/View.cshtml" };
                    result.ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
                    result.ViewData.Add("Exception", context.Exception);
                    context.Result = result; //阻断下面的执行
                }

                context.ExceptionHandled = true; // 这里表示异常被处理过
            }
        }
        /// <summary>
        /// 当异常发生的时候，就会触发这里，有异步，同步就不执行了
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        //public Task OnExceptionAsync(ExceptionContext context)
        //{
        //    Console.WriteLine("异常发生异步方法");
            
        //}


        private bool isAjaxRequest(HttpRequest request)
        {
            string header = request.Headers["X-Requested-With"];
            return "XMLHttpRequest".Equals(header);
        }
    }
}
